package com.x.rocketmq.init;

import com.x.rocketmq.content.RocketMQContents;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RocketMQProducerInit
{
	
	private Logger logger = LoggerFactory.getLogger(RocketMQProducerInit.class);
	
	private DefaultMQProducer defaultMQProducer;
	
	/** 生产者实例ID */
	private Long id = (long) -1;
	
	/** 生产者分组 */
	private String producerGroup;
	
	/** rocketMQ 名称服务器 */
	private String namesrvAddr;
	
	/** 生产者服务对象 */
	private String producerInstanceName;

	/**
	 * PostConstruct修饰的方法会在服务器加载Servle的时候运行，并且只会被服务器执行一次。
	 * PostConstruct在构造函数之后执行,init()方法之前执行。PreDestroy（）方法在destroy()方法执行执行之后执行
	 */
	public void init() throws MQClientException
	{
		defaultMQProducer = new DefaultMQProducer(producerGroup);
		defaultMQProducer.setNamesrvAddr(namesrvAddr);
		//必须设为false否则连接broker10909端口
		defaultMQProducer.setVipChannelEnabled(false);
		if (StringUtils.isEmpty(producerInstanceName))
		{
			producerInstanceName = producerGroup;
		}
		defaultMQProducer.setInstanceName(producerInstanceName);
		defaultMQProducer.start();
		
		RocketMQContents.ROCKETMQ_PRODUCER.put(id, this);
		logger.info(
				"RocketMQProducerInit defaultMQProducer=" + defaultMQProducer + ", producerGroup=" + producerGroup + ", namesrvAddr=" + namesrvAddr + ", producerInstanceName=" + producerInstanceName);
	}
	
	/**
	 * 程序销毁
	 */
	public void destroy()
	{
		defaultMQProducer.shutdown();
	}
	
	public DefaultMQProducer getDefaultMQProducer()
	{
		return defaultMQProducer;
	}
	
	public void setDefaultMQProducer(DefaultMQProducer defaultMQProducer)
	{
		this.defaultMQProducer = defaultMQProducer;
	}
	
	public String getProducerGroup()
	{
		return producerGroup;
	}
	
	public void setProducerGroup(String producerGroup)
	{
		this.producerGroup = producerGroup;
	}
	
	public String getNamesrvAddr()
	{
		return namesrvAddr;
	}
	
	public void setNamesrvAddr(String namesrvAddr)
	{
		this.namesrvAddr = namesrvAddr;
	}
	
	public String getProducerInstanceName()
	{
		return producerInstanceName;
	}
	
	public void setProducerInstanceName(String producerInstanceName)
	{
		this.producerInstanceName = producerInstanceName;
	}
	
	public Long getId()
	{
		return id;
	}
	
	public void setId(Long id)
	{
		this.id = id;
	}
	
	@Override
	public String toString()
	{
		return "RocketMQProducerInit [defaultMQProducer=" + defaultMQProducer + ", producerGroup=" + producerGroup + ", namesrvAddr=" + namesrvAddr + ", producerInstanceName=" + producerInstanceName
				+ "]";
	}
	
}
